import { defineStore } from "pinia";

import { ref } from "vue";

import type { Ref } from "vue";

interface isUser {
    loggedIn: boolean;
    userId: string;
    token: string
}

export const useUserStore = defineStore('user', () => {
    // 定义全局状态
    // 登录状态
    const loggedIn: Ref<boolean> = ref(localStorage.getItem('loggedIn') == 'true')
    // 用户id
    const userId: Ref<string> = ref(localStorage.getItem('userId') || '')
    // 用户token
    const token: Ref<string> = ref(localStorage.getItem('token') || '')

    // 定义修改方法
    function changeUserState(userInfo: isUser) {
        loggedIn.value = userInfo.loggedIn
        userId.value = userInfo.userId
        token.value = userInfo.token


        // 将数据存储到本地
        localStorage.setItem('loggedIn', JSON.stringify(userInfo.loggedIn))
        localStorage.setItem('userId', userInfo.userId)
        localStorage.setItem('token', userInfo.token)
    }


    // 暴露全局状态和方法
    return {
        changeUserState,
        loggedIn,
        userId,
        token

    }
})